package net.sudot.chess.security;

import net.sudot.commons.security.SocialUserAuthenticationToken;
import net.sudot.commons.utils.Pbkdf2PasswordEncoder;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

/**
 * PBKDF2 salted password hashing.
 *
 * @author tangjialin on 2018-12-12.
 */
public class Pbkdf2CredentialsMatcher extends SimpleCredentialsMatcher {
    @Override
    protected boolean equals(Object tokenCredentials, Object accountCredentials) {
        if (isByteSource(tokenCredentials) && isByteSource(accountCredentials)) {
            String tokenString = toString(tokenCredentials);
            String correctHash = toString(accountCredentials);
            return Pbkdf2PasswordEncoder.validatePassword(tokenString, correctHash);
        } else {
            throw new CredentialsException("不支持的密码类型");
        }
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        if (token instanceof SocialUserAuthenticationToken) { return true; }
        return super.doCredentialsMatch(token, info);
    }
}
